package cn.edu.zime.tjh.iotapp;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import cn.edu.zime.tjh.iotapp.api.ApiService;
import cn.edu.zime.tjh.iotapp.api.StreamingChatCallback;
import cn.edu.zime.tjh.iotapp.chat.ChatAdapter;
import cn.edu.zime.tjh.iotapp.chat.ChatMessage;

public class ChatActivity extends AppCompatActivity {
    
    private static final String TAG = "ChatActivity";
    
    private RecyclerView recyclerView;
    private EditText editTextMessage;
    private Button buttonSend;
    
    private ChatAdapter adapter;
    private List<ChatMessage> messageList;
    
    private ApiService apiService;
    private ChatMessage currentBotMessage;
    private boolean isReceivingResponse = false;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        
        // 初始化API服务
        apiService = ApiService.getInstance();
        
        // 初始化UI组件
        initViews();
        
        // 设置消息列表
        setupMessageList();
        
        // 设置发送按钮点击事件
        buttonSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage();
            }
        });
        
        // 添加欢迎消息
        addBotMessage("您好！我是智能助手，有什么可以帮助您的吗？");
    }
    
    private void initViews() {
        recyclerView = findViewById(R.id.recyclerView);
        editTextMessage = findViewById(R.id.editTextMessage);
        buttonSend = findViewById(R.id.buttonSend);
        
        // 设置标题
        TextView titleText = findViewById(R.id.textTitle);
        if (titleText != null) {
            titleText.setText("在线聊天");
        }
    }
    
    private void setupMessageList() {
        messageList = new ArrayList<>();
        adapter = new ChatAdapter(messageList);
        
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }
    
    private void sendMessage() {
        final String messageText = editTextMessage.getText().toString().trim();
        if (messageText.isEmpty()) {
            return;
        }
        
        // 如果正在接收响应，不允许发送新消息
        if (isReceivingResponse) {
            Toast.makeText(this, "请等待AI响应完成...", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 清空输入框
        editTextMessage.setText("");
        
        // 添加到消息列表
        addUserMessage(messageText);
        
        // 创建一个空的机器人消息（将在流式接收时更新）
        startBotResponse();
        
        // 发送到服务器
        apiService.sendChatMessage(messageText, new StreamingChatCallback() {
            @Override
            public void onPartialResponse(String partialContent) {
                updateBotMessage(partialContent);
            }
            
            @Override
            public void onComplete(String completeContent) {
                finishBotResponse();
            }
            
            @Override
            public void onError(String errorMsg) {
                Log.e(TAG, "发送聊天消息失败: " + errorMsg);
                Toast.makeText(ChatActivity.this, "发送失败: " + errorMsg, Toast.LENGTH_SHORT).show();
                
                // 更新当前bot消息显示错误
                updateBotMessageWithError("抱歉，网络连接出现问题，请稍后再试。");
            }
        });
    }
    
    private void addUserMessage(String message) {
        ChatMessage chatMessage = new ChatMessage(ChatMessage.TYPE_SENT, message);
        messageList.add(chatMessage);
        adapter.notifyItemInserted(messageList.size() - 1);
        recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
    }
    
    private void addBotMessage(String message) {
        ChatMessage chatMessage = new ChatMessage(ChatMessage.TYPE_RECEIVED, message);
        messageList.add(chatMessage);
        adapter.notifyItemInserted(messageList.size() - 1);
        recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
    }
    
    // 开始接收机器人响应
    private void startBotResponse() {
        isReceivingResponse = true;
        
        // 创建一个空的机器人消息
        currentBotMessage = new ChatMessage(ChatMessage.TYPE_RECEIVED, "");
        messageList.add(currentBotMessage);
        adapter.notifyItemInserted(messageList.size() - 1);
        recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
    }
    
    // 更新正在接收的机器人消息
    private void updateBotMessage(String additionalContent) {
        if (currentBotMessage != null) {
            // 更新当前消息的内容
            String currentContent = currentBotMessage.getMessage();
            currentBotMessage.updateMessage(currentContent + additionalContent);
            
            // 通知适配器更新这一项
            int position = messageList.indexOf(currentBotMessage);
            if (position >= 0) {
                adapter.notifyItemChanged(position);
                recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
            }
        }
    }
    
    // 完成机器人响应接收
    private void finishBotResponse() {
        isReceivingResponse = false;
        currentBotMessage = null;
    }
    
    // 显示错误消息
    private void updateBotMessageWithError(String errorMessage) {
        if (currentBotMessage != null) {
            currentBotMessage.updateMessage(errorMessage);
            
            int position = messageList.indexOf(currentBotMessage);
            if (position >= 0) {
                adapter.notifyItemChanged(position);
            }
        }
        
        isReceivingResponse = false;
        currentBotMessage = null;
    }
    
    public void back(View view) {
        finish();
    }
} 